package com.yzion.baselib.http.lifecycle

import android.app.Dialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import retrofit2.Call
import java.util.concurrent.ConcurrentHashMap

val callLifecycleObserverMap = ConcurrentHashMap<Call<*>, CallLifecycleObserver>()

//移除无用观察者
private fun check() {
    runCatching {
        callLifecycleObserverMap.values.toList().forEach {
            if (it.call.isCanceled || it.call.isExecuted) {
                it.removeObserver()
            }
        }
    }
}

/**
 * 接口请求在Dialog关闭时，如果还在请求中则取消
 */
fun Call<*>.cancelOnDismiss(dialog: Dialog): Call<*> {
    check()
    dialog.setOnDismissListener {
        if (isCanceled.not()) {
            cancel()
        } else {
            unbindToLifeCycle()
        }
    }
    return this
}

/**
 * 接口请求在DialogFragment关闭时，如果还在请求中则取消
 */
fun Call<*>.cancelOnDismiss(dialogFragment: DialogFragment): Call<*> {
    check()
    callLifecycleObserverMap[this] = CallLifecycleObserver(dialogFragment.lifecycle, this)
    return this
}

/**
 * 接口请求在Activity销毁时，如果还在请求中则取消
 */
fun Call<*>.cancelOnDestroy(appCompatActivity: AppCompatActivity): Call<*> {
    check()
    callLifecycleObserverMap[this] = CallLifecycleObserver(appCompatActivity.lifecycle, this)
    return this
}

/**
 * 接口请求在Fragment销毁时，如果还在请求中则取消
 */
fun Call<*>.cancelOnDestroy(fragment: Fragment): Call<*> {
    check()
    callLifecycleObserverMap[this] = CallLifecycleObserver(fragment.lifecycle, this)
    return this
}

/**
 * 当Call执行完成后可以调用解除绑定
 */
fun Call<*>.unbindToLifeCycle(): Call<*> {
    callLifecycleObserverMap[this]?.let {
        it.removeObserver()
    }
    return this
}